/**   
* @Title: MQProducerImpl.java 
* @Package com.cyl.rabbitmq 
* @Description: TODO(��һ�仰�������ļ���ʲô) 
* @author zjhua@hundsun.com   
* @date 2016��4��25�� ����1:12:46 
* @version V1.0   
*/
package com.medsoft.dlcache.mq;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * @author zjhua
 *
 */
@Service
public class MQProducerImpl implements InitializingBean,MQProducer {

	@Autowired
    private ConnectionFactory connectionFactory;
	
	@Value("${localcache.publishExchanges}")
	private String publishExchanges;
	
	private static Map<String,Channel> channelMap = new HashMap<String,Channel>();

    /* (non-Javadoc)
	 * @see com.cyl.rabbitmq.MQProducer#sendDataToQueue(java.lang.String, java.lang.Object)
	 */
	@Override
	public boolean sendDataToQueue(String exchange,String routeKey, Object object) {
		try {
			channelMap.get(exchange).basicPublish(exchange, "", null, object.toString().getBytes());
			return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
	}

	/* (non-Javadoc)
	 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
	 */
	@Override
	public void afterPropertiesSet() throws Exception {
		if(publishExchanges == null || publishExchanges.trim().equals(""))
		{
			System.out.println("本地缓存发布队列参数[localcache.publishExchanges]没有设置，请检查server.properties");
			return;
		}
		Connection connection = connectionFactory.newConnection();

		for (String publishExchange : Arrays.asList(this.publishExchanges.split(","))) {
			Channel channel = connection.createChannel();
			channel.exchangeDeclare(publishExchange, "fanout");
			channelMap.put(publishExchange,channel);
		}
	}
}
